// 导入更新脚本
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 文件路径映射
const pathMapping = {
  // 视频相关
  '@/lib/hls-optimizer': '@/lib/video/hls-optimizer',
  '@/lib/hls-metrics': '@/lib/video/hls-metrics',
  '@/lib/video-events': '@/lib/video/video-events',
  '@/lib/video-service': '@/lib/video/video-service',
  
  // 服务相关
  '@/lib/session-service': '@/lib/services/session-service',
  '@/lib/simple-crawler-service': '@/lib/services/simple-crawler-service',
  '@/lib/banner-crawler-service': '@/lib/services/banner-crawler-service',
  '@/lib/crawler-service': '@/lib/services/crawler-service',
  
  // 认证相关
  '@/lib/auth-utils': '@/lib/auth/auth-utils',
  
  // 工具和辅助函数
  '@/lib/utils': '@/lib/utils/utils',
  '@/lib/fetch': '@/lib/utils/fetch',
  '@/lib/metadata': '@/lib/utils/metadata',
  '@/lib/types': '@/lib/utils/types',
  
  // 配置和常量
  '@/lib/env-setup': '@/lib/config/env-setup',
  '@/lib/constants': '@/lib/config/constants',
  
  // API相关
  '@/lib/prisma': '@/lib/api/prisma',
  
  // 相对路径映射（用于脚本等）
  '../lib/crawler-service': '../lib/services/crawler-service',
  '../lib/banner-crawler-service': '../lib/services/banner-crawler-service',
  '../lib/simple-crawler-service': '../lib/services/simple-crawler-service'
};

// 获取所有TypeScript和TSX文件
const getAllFiles = (dir, fileList = []) => {
  const files = fs.readdirSync(dir);
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory() && !filePath.includes('node_modules') && !filePath.includes('.next')) {
      fileList = getAllFiles(filePath, fileList);
    } else if ((filePath.endsWith('.ts') || filePath.endsWith('.tsx') || filePath.endsWith('.js') || filePath.endsWith('.jsx')) && 
               !filePath.includes('node_modules') && !filePath.includes('.next')) {
      fileList.push(filePath);
    }
  });
  
  return fileList;
};

// 更新文件中的导入路径
const updateImports = (filePath) => {
  let content = fs.readFileSync(filePath, 'utf8');
  let updated = false;
  
  // 检查并替换导入路径
  Object.keys(pathMapping).forEach(oldPath => {
    const newPath = pathMapping[oldPath];
    const regex = new RegExp(`from ['"](${oldPath})['"]`, 'g');
    
    if (regex.test(content)) {
      content = content.replace(regex, `from '${newPath}'`);
      updated = true;
    }
  });
  
  // 如果文件被更新，则写回
  if (updated) {
    fs.writeFileSync(filePath, content, 'utf8');
    console.log(`Updated imports in: ${filePath}`);
  }
};

// 主函数
const main = () => {
  console.log('开始更新导入路径...');
  
  // 获取项目根目录下的所有TypeScript和TSX文件
  const files = getAllFiles(path.resolve(__dirname, '..'));
  
  // 更新每个文件中的导入路径
  files.forEach(file => {
    updateImports(file);
  });
  
  console.log('导入路径更新完成！');
};

main(); 